<?php
namespace app\admin\controller;
use support\exception\ValidateException;
use app\admin\model\Membe as MembeModel;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Cache;

class MembeController extends CommonController{



	/**
	 *@description 数据列表
	 *@buildcode(true)
	*/
	function index(){
		if($this->request->method() == 'GET'){
			return view('membe/index');
		}else{
			$limit  = $this->request->post('limit', 20, 'intval');
			$page = $this->request->post('page', 1, 'intval');

			$field = 'membe_id,username,sex,mobile,pic,email,status,amount,ssq,create_time';
			$query = MembeModel::field($field);

			$param = $this->request->post();
			if(isset($param['membe_id']) && !empty($param['membe_id'])) {
				$query = $query->where("membe_id", $param['membe_id']);
			}
			if(isset($param['username']) && $param['username'] != null) {
				$query = $query->where("username", $param['username']);
			}
			if(isset($param['sex']) && $param['sex'] != null) {
				$query = $query->where("sex", $param['sex']);
			}
			if(isset($param['mobile']) && $param['mobile'] != null) {
				$query = $query->where("mobile", $param['mobile']);
			}
			if(isset($param['email']) && $param['email'] != null) {
				$query = $query->where("email", $param['email']);
			}
			if(isset($param['status']) && $param['status'] != null) {
				$query = $query->where("status", $param['status']);
			}
			if(isset($param['amount']) && $param['amount'] != null) {
				$query = $query->where("amount", $param['amount']);
			}
			if(isset($param['ssq']) && $param['ssq'] != null) {
				$query = $query->whereLike('ssq',"%".implode('-',$param['ssq'])."%");
			}
			if(isset($param['create_time']) && $param['create_time'] != null) {
				$query = $query->whereBetween('create_time', [strtotime($param['create_time'][0]),strtotime($param['create_time'][1])]);
			}
			$orderby = ($param['sort'] && $param['order']) ? $param['sort'].' '.$param['order'] : 'membe_id desc';

			$res =$query->order($orderby)->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();

			$data['status'] = 200;
			$data['data'] = $res;
			$data['sum_amount'] = $query->sum('amount');
			return json($data);
		}
	}


	/**
	 *@description 修改排序开关
	 *@buildcode(true)
	*/
	function updateExt(){
		$postField = 'membe_id,status';
		$data = $this->request->only(explode(',',$postField),'post');
		if(!$data['membe_id']) throw new ValidateException ('参数错误');
		MembeModel::update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


	/**
	 *@description 添加
	 *@buildcode(true)
	*/
	public function add(){
		$postField = 'username,sex,mobile,pic,email,password,status,amount,ssq,create_time';
		$data = $this->request->only(explode(',',$postField),'post');

		$validate = new \app\admin\validate\MembeValidate;
		if(!$validate->scene('add')->check($data)){
			throw new ValidateException ($validate->getError());
		}

		$data['password'] = md5($data['password'].config('my.password_secrect'));
		$data['ssq'] = is_array($data['ssq']) ? implode('-',$data['ssq']) : '';
		$data['create_time'] = time();

		try{
			$res = MembeModel::insertGetId($data);
		}catch(\Exception $e){
			throw new ValidateException($e->getMessage());
		}

		if($ret = hook('hook/Membe@afterAdminAdd',array_merge($data,['membe_id'=>$res]))){
			return $ret;
		}

		return json(['status'=>200,'data'=>$res,'msg'=>'添加成功']);
	}


	/**
	 *@description 修改
	 *@buildcode(true)
	*/
	public function update(){
		$postField = 'membe_id,username,sex,mobile,pic,email,status,amount,ssq,create_time';
		$data = $this->request->only(explode(',',$postField),'post');

		$validate = new \app\admin\validate\MembeValidate;
		if(!$validate->scene('update')->check($data)){
			throw new ValidateException ($validate->getError());
		}

		$data['ssq'] = is_array($data['ssq']) ? implode('-',$data['ssq']) : '';
		$data['create_time'] = !empty($data['create_time']) ? strtotime($data['create_time']) : '';

		try{
			MembeModel::update($data);
		}catch(\Exception $e){
			throw new ValidateException($e->getMessage());
		}
		return json(['status'=>200,'msg'=>'修改成功']);
	}


	/**
	 *@description 修改信息之前查询信息的
	 *@buildcode(true)
	*/
	function getUpdateInfo(){
		$id =  $this->request->post('membe_id');
		if(!$id) throw new ValidateException ('参数错误');
		$field = 'membe_id,username,sex,mobile,pic,email,status,amount,ssq,create_time';
		$res = MembeModel::field($field)->find($id);
		$res['ssq'] = !empty($res['ssq']) ? explode('-',$res['ssq']) : '';
		return json(['status'=>200,'data'=>$res]);
	}


	/**
	 *@description 删除
	 *@buildcode(true)
	*/
	function delete(){
		$idx =  $this->request->post('membe_id');
		if(!$idx) throw new ValidateException ('参数错误');
		MembeModel::destroy(['membe_id'=>explode(',',$idx)],true);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


	/**
	 *@description 查看详情
	 *@buildcode(true)
	*/
	function detail(){
		$id =  $this->request->post('membe_id');
		if(!$id) throw new ValidateException ('参数错误');
		$field = 'membe_id,username,sex,mobile,pic,email,status,amount,ssq,create_time';
		$res = MembeModel::field($field)->findOrEmpty($id);

		if($res->isEmpty()){
			throw new ValidateException ('信息不存在');
		}

		return json(['status'=>200,'data'=>$res]);
	}


	/**
	 *@description 导入
	 *@buildcode(true)
	*/
	public function importData(){
		$data = $this->request->post();
		$list = [];
		foreach($data as $key=>$val){
			$list[$key]['username'] = !empty($val['用户名']) ? $val['用户名'] : '';
			$list[$key]['sex'] = !empty($val['性别']) ? getValByKey($val['性别'],'[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]') : '';
			$list[$key]['mobile'] = !empty($val['手机号']) ? $val['手机号'] : '';
			$list[$key]['pic'] = !empty($val['头像']) ? $val['头像'] : '';
			$list[$key]['email'] = !empty($val['邮箱']) ? $val['邮箱'] : '';
			$list[$key]['password'] = !empty($val['密码']) ? md5($val['密码']) : '';
			$list[$key]['status'] = !empty($val['状态']) ? getValByKey($val['状态'],'[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]') : '';
			$list[$key]['amount'] = !empty($val['积分']) ? $val['积分'] : '';
			$list[$key]['ssq'] = !empty($val['省市区']) ? $val['省市区'] : '';
			$list[$key]['create_time'] = time();
		}
		(new MembeModel)->insertAll($list);
		return json(['status'=>200]);
	}


	/**
	 *@description 客户端导出
	 *@buildcode(true)
	*/
	function dumpdata(){
		$page = $this->request->input('page', 1, 'intval');
		$limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;

		$state = $this->request->input('state');
		$searchField = 'username,sex,mobile,email,status,amount,ssq,create_time,order,sort';
		$param = $this->request->only(explode(',',$searchField),'post');

		$field = 'username,sex,mobile,pic,email,password,status,amount,ssq,create_time';

		$query = MembeModel::field($field);

		if(isset($param['membe_id']) && !empty($param['membe_id'])) {
			$query = $query->where("membe_id", $param['membe_id']);
		}
		if(isset($param['username']) && $param['username'] != null) {
			$query = $query->where("username", $param['username']);
		}
		if(isset($param['sex']) && $param['sex'] != null) {
			$query = $query->where("sex", $param['sex']);
		}
		if(isset($param['mobile']) && $param['mobile'] != null) {
			$query = $query->where("mobile", $param['mobile']);
		}
		if(isset($param['email']) && $param['email'] != null) {
			$query = $query->where("email", $param['email']);
		}
		if(isset($param['status']) && $param['status'] != null) {
			$query = $query->where("status", $param['status']);
		}
		if(isset($param['amount']) && $param['amount'] != null) {
			$query = $query->where("amount", $param['amount']);
		}
		if(isset($param['ssq']) && $param['ssq'] != null) {
			$query = $query->whereLike('ssq',"%".implode('-',$param['ssq'])."%");
		}
		if(isset($param['create_time']) && $param['create_time'] != null) {
			$query = $query->whereBetween('create_time', [strtotime($param['create_time'][0]),strtotime($param['create_time'][1])]);
		}
		$orderby = ($param['sort'] && $param['order']) ? $param['sort'].' '.$param['order'] : 'membe_id desc';

		$res =$query->order($orderby)->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();

		foreach($res['data'] as $key=>$val){
			$res['data'][$key]['sex'] = getItemVal($val['sex'],'[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]');
			$res['data'][$key]['status'] = getItemVal($val['status'],'[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]');
			$res['data'][$key]['create_time'] = !empty($val['create_time']) ? date('Y-m-d',$val['create_time']) : '';
			unset($res['data'][$key]['membe_id']);
		}

		$data['status'] = 200;
		$data['header'] = explode(',','用户名,性别,手机号,头像,邮箱,密码,状态,积分,省市区,创建时间');
		$data['percentage'] = ceil($page * 100/ceil($res['total']/$limit));
		$data['filename'] = '会员管理.'.config('my.dump_extension');
		$data['data'] = $res['data'];
		return json($data);
	}


	/**
	 *@description 服务端导出
	 *@buildcode(true)
	*/
	function dumpdata2(){
		$page = $this->request->input('page', 1, 'intval');
		$limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;

		$state = $this->request->input('state');
		$searchField = 'username,sex,mobile,email,status,amount,ssq,create_time,order,sort';
		$param = $this->request->only(explode(',',$searchField),'post');

		$field = 'username,sex,mobile,pic,email,password,status,amount,ssq,create_time';

		$query = MembeModel::field($field);

		if(isset($param['membe_id']) && !empty($param['membe_id'])) {
			$query = $query->where("membe_id", $param['membe_id']);
		}
		if(isset($param['username']) && $param['username'] != null) {
			$query = $query->where("username", $param['username']);
		}
		if(isset($param['sex']) && $param['sex'] != null) {
			$query = $query->where("sex", $param['sex']);
		}
		if(isset($param['mobile']) && $param['mobile'] != null) {
			$query = $query->where("mobile", $param['mobile']);
		}
		if(isset($param['email']) && $param['email'] != null) {
			$query = $query->where("email", $param['email']);
		}
		if(isset($param['status']) && $param['status'] != null) {
			$query = $query->where("status", $param['status']);
		}
		if(isset($param['amount']) && $param['amount'] != null) {
			$query = $query->where("amount", $param['amount']);
		}
		if(isset($param['ssq']) && $param['ssq'] != null) {
			$query = $query->whereLike('ssq',"%".implode('-',$param['ssq'])."%");
		}
		if(isset($param['create_time']) && $param['create_time'] != null) {
			$query = $query->whereBetween('create_time', [strtotime($param['create_time'][0]),strtotime($param['create_time'][1])]);
		}
		$orderby = ($param['sort'] && $param['order']) ? $param['sort'].' '.$param['order'] : 'membe_id desc';

		$res =$query->order($orderby)->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();

		$cache_key = 'Membe';
		if($page == 1){
			Cache::set($cache_key,[]);
		}
		$totalpage = ceil($res['total']/$limit);
		Cache::set($cache_key,array_merge(Cache::get($cache_key),$res['data']));

		if($page < $totalpage){
			$data['percentage'] = ceil($page * 100/$totalpage);
			$data['state'] =  'ok';
			return json($data);
		}else{
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$sheet->setCellValue('A1','用户名');
			$sheet->setCellValue('B1','性别');
			$sheet->setCellValue('C1','手机号');
			$sheet->setCellValue('D1','头像');
			$sheet->setCellValue('E1','邮箱');
			$sheet->setCellValue('F1','密码');
			$sheet->setCellValue('G1','状态');
			$sheet->setCellValue('H1','积分');
			$sheet->setCellValue('I1','省市区');
			$sheet->setCellValue('J1','创建时间');

			foreach(Cache::get($cache_key) as $k=>$v){
				$sheet->setCellValue('A'.($k+2),$v['username']);
				$sheet->setCellValue('B'.($k+2),getItemVal($v['sex'],'[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]'));
				$sheet->setCellValue('C'.($k+2),$v['mobile']);
				$sheet->setCellValue('D'.($k+2),$v['pic']);
				$sheet->setCellValue('E'.($k+2),$v['email']);
				$sheet->setCellValue('F'.($k+2),$v['password']);
				$sheet->setCellValue('G'.($k+2),getItemVal($v['status'],'[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]'));
				$sheet->setCellValue('H'.($k+2),$v['amount']);
				$sheet->setCellValue('I'.($k+2),$v['ssq']);
				$sheet->setCellValue('J'.($k+2),!empty($v['create_time']) ? date('Y-m-d',$v['create_time']) : '');
			}

			Cache::set($cache_key,[]);

			$filename = '会员管理.'.config('my.dump_extension');
			$writer = new Xlsx($spreadsheet);
            $dir = public_path().'/uploads/excel';
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
			$file_path = $dir.'/'.$filename;
			$writer->save($file_path);
			return response()->download($file_path, $filename);
		}
	}


	/**
	 *@description 重置密码
	 *@buildcode(true)
	*/
	public function resetPwd(){
		$postField = 'membe_id,password';
		$data = $this->request->only(explode(',',$postField),'post');
		if(empty($data['membe_id'])) throw new ValidateException ('参数错误');
		if(empty($data['password'])) throw new ValidateException ('密码不能为空');

		$data['password'] = md5($data['password'].config('my.password_secrect'));
		$res = MembeModel::update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


	/**
	 *@description 禁用
	 *@buildcode(true)
	*/
	public function forbidden(){
		$idx = $this->request->post('membe_id');
		if(empty($idx)) throw new ValidateException ('参数错误');

		$data['status'] = 0;
		$res = MembeModel::where(['membe_id'=>explode(',',$idx)])->update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


}